package lib.quasar.base.http.interceptor;

import android.text.TextUtils;

import com.google.gson.GsonBuilder;

import lib.quasar.base.BuildConfig;
import lib.quasar.context.BaseConstant;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lib.quasar.db.manager.DBManager;
import lib.quasar.db.table.Http;
import lib.quasar.util.LogUtil;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * description: okhttp拦截器(缓存数据统一处理)
 * created by kalu on 2017/5/15 10:34
 */
public final class HttpInterceptor implements Interceptor {

    private final String TAG = HttpInterceptor.class.getSimpleName();

    // log日志
    private final StringBuilder logBuilder = new StringBuilder();

    private final String VERSION = String.valueOf(BuildConfig.VERSION_CODE);
    // android+系统版本+手机厂商+手机型号
    private final String PLATFORM = "android+" + android.os.Build.VERSION.RELEASE + "+" + android.os.Build.BRAND + "+" + android.os.Build.MODEL;

    /**********************************************************************************************/

    public HttpInterceptor() {
    }

    /**********************************************************************************************/

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();

        // 请求URL
        final String url = request.url().toString();

        // 下载文件
        boolean isDownload = ("1".equals(request.header("xDownload")));

        // 下载请求
        if (isDownload) {

            LogUtil.e(TAG, "intercept[下载apk] ==> url = " + url);

            Response proceed = chain.proceed(requestBuilder.build());
            return proceed
                    .newBuilder()
                    .body(proceed.body())
                    .build();
        }
        // 普通请求
        else {

            // 是否需要缓存
            boolean needCache = (BaseConstant.ONE.equals(request.header(BaseConstant.X_CACHED)));

            // 是否需要登录
            boolean needLogin = (BaseConstant.ONE.equals(request.header(BaseConstant.X_LOGIN)));

            requestBuilder.addHeader("version", VERSION);
            requestBuilder.addHeader("platform", PLATFORM);

            // 自定义User-Agent
            requestBuilder.addHeader("User-Agent", "android");
            requestBuilder.addHeader("Cache-Control", "no-cache");

            // 开发环境
            if (BaseConstant.IS_DEBUG) {
                logBuilder.delete(0, logBuilder.length());
                logBuilder.append("====> Http " + request.method() + " url = ")
                        .append(url)
                        .append('\n');
                logBuilder.append("====> Http header: xCached = ").append(needCache)
                        .append(", xLogin = ").append(needLogin)
                        .append('\n');

                // POST请求
                if (BaseConstant.POST.equalsIgnoreCase(request.method())) {
                    RequestBody requestBody = request.body();
                    if (requestBody instanceof FormBody) {
                        FormBody formBody = (FormBody) requestBody;
                        int size = formBody.size();
                        Map<String, String> map = new HashMap<>(size);
                        for (int i = 0; i < size; i++) {
                            map.put(formBody.name(i), formBody.value(i));
                        }

                        if (BaseConstant.IS_DEBUG) {
                            logBuilder.append("====> Http Post Parameters = ")
                                    .append(new GsonBuilder().setPrettyPrinting().create().toJson(map))
                                    .append('\n');
                        }
                    }
                }
            }

            // 需要登录
            if (needLogin) {

                    // 添加公共参数
                    HttpUrl httpUrl = request.url().newBuilder()
                            .addQueryParameter("nonce", "")
                            .addQueryParameter("timestamp", "")
                            .addQueryParameter("sign", "")
                            .build();

                    Map<String, Object> map = new HashMap<>();

                    if (BaseConstant.IS_DEBUG) {
                        logBuilder.append("====> Http Auth Parameters = ")
                                .append(new GsonBuilder().setPrettyPrinting().create().toJson(map))
                                .append('\n');
                    }

                    requestBuilder.url(httpUrl);
            }

            Response response;
            try {
                response = chain.proceed(requestBuilder.build());
                // Looper.prepare();
                // ToastUtil.showToast("响应码" + response.code());

                if (needCache) {
                    LogUtil.e(TAG, "====> Net[网络正常, 需要缓存], responseCode = " + response.code());

                    ResponseBody responseBody = response.body();
                    String body = responseBody.string();

                    if (response.isSuccessful()) {
//                        HttpResult httpResult = new Gson().fromJson(body, HttpResult.class);
//
//                        // 请求成功，data不为null，写缓存
//                        if (!TextUtils.isEmpty(httpResult.getMsgCode()) && "0x00000010".equals(httpResult.getMsgCode()) && !body.contains("\"data\":null")) {
//
//                            // 1. 读取最近保存的缓存
//                            List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
//                            if (null != list && list.size() > 0) {
//
//                                HttpJson cache = list.get(0);
//                                if (null != cache && !cache.getJson().equals(body)) {
//                                    LogUtil.e(TAG, "====> Net[网络正常, DATA存在,  缓存存在, JSON更新]");
//                                    cache.setJson(body);
//                                    DBManager.getHttpJsonDao().update(cache);
//                                } else {
//                                    LogUtil.e(TAG, "====> Net[网络正常, DATA存在,  缓存存在, JSON不变]");
//                                }
//                            } else {
//                                LogUtil.e(TAG, "====> Net[网络正常, DATA存在, 缓存为空, JSON保存]");
//                                HttpJson model = new HttpJson();
//                                model.setUrl(url);
//                                model.setJson(body);
//                                DBManager.getHttpJsonDao().insert(model);
//                            }
//
//                            if (LogUtil.DEBUG) {
//                                logBuilder.append("====> Http response[web] = ").append(body);
//                            }
//                        } else {
                        LogUtil.e(TAG, "====> Net[网络正常, DATA为空]");

                        // 请求成功，data为null，读缓存，并重新构建response
                        List<Http> list = DBManager.getInstance().getHttplList(url);
                        if (null != list && list.size() > 0) {
                            Http cache = list.get(0);

                            if (null != cache && !TextUtils.isEmpty(cache.getJson())) {
                                body = cache.getJson();

                                if (BaseConstant.IS_DEBUG) {
                                    logBuilder.append("====> Http response[cache] = ").append(body);
                                }
                            }
                        }
//                        }

                    } else {
                        // 请求失败，读缓存，并重新构建response

                        List<Http> list = DBManager.getInstance().getHttplList(url);
                        if (null != list && list.size() > 0) {
                            Http cache = list.get(0);

                            if (null != cache && !TextUtils.isEmpty(cache.getJson())) {
                                body = cache.getJson();

                                if (BaseConstant.IS_DEBUG) {
                                    logBuilder.append("====> Http response[cache] = ").append(body);
                                }
                            }
                        }
                    }
                    return response.newBuilder()
                            .body(ResponseBody.create(responseBody.contentType(), body))
                            .build();

                } else {
                    LogUtil.e(TAG, "====> Net[网络正常, 不要缓存], responseCode = " + response.code());

                    ResponseBody responseBody = response.body();
                    String body = responseBody.string();

                    if (BaseConstant.IS_DEBUG) {
                        logBuilder.append("====> Http response[网络] = ").append(body);
                    }

//                    return new Response.Builder()
//                            .code(200)
//                            .message("OK, but from cache")
//                            .protocol(Protocol.HTTP_1_1)
//                            .request(request)
//                            .body(ResponseBody.create(MediaType.parse("application/json"), "{\"msgCode\":\"00010003\",\"checkCode\":\"\",\"msg\":\"用户名不存在\",\"msgDatas\":null}"))
//                            .build();

                    return response.newBuilder()
                            .body(ResponseBody.create(responseBody.contentType(), body))
                            .build();
                }
            } catch (Exception e) {
                LogUtil.e(TAG, e.getMessage(), e);

                if (needCache) {
                    LogUtil.e(TAG, "====> Net[网络异常, 需要缓存]");

                    // 请求失败，读缓存，并重新构建response
                    List<Http> list = DBManager.getInstance().getHttplList(url);
                    if (null != list && list.size() > 0) {

                        Http cache = list.get(0);

                        if (null != cache) {

                            String json = cache.getJson();

                            if (!TextUtils.isEmpty(json)) {
                                LogUtil.e(TAG, "====> Net[网络异常, 缓存存在, JSON存在]");

                                if (BaseConstant.IS_DEBUG) {
                                    logBuilder.append("====> Http response[cache] = ").append(json);
                                }

                                // 重新构建 200 的请求
                                return new Response.Builder()
                                        .code(200)
                                        .message("OK, but from cache")
                                        .protocol(Protocol.HTTP_1_1)
                                        .request(request)
                                        .body(ResponseBody.create(MediaType.parse("application/json"), json))
                                        .build();
                            } else {
                                LogUtil.e(TAG, "====> Net[网络异常, 缓存存在, JSON为空]");
                            }
                        } else {
                            LogUtil.e(TAG, "====> Net[网络异常, 缓存为空]");
                        }
                    } else {
                        LogUtil.e(TAG, "====> Net[网络异常, 缓存为空]");
                    }
                } else {
                    LogUtil.e(TAG, "====> Net[网络异常, 不要缓存]");
                }
                throw e;
            } finally {
                LogUtil.e(TAG, logBuilder.toString());
            }
        }
    }
}
